package com.steven.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ChatClient1 {

    private static  final String HOST="127.0.0.1";
    private static  final Integer PORT=10010;

    private  Selector selector;
    private  SocketChannel socketChannel;
    private  String userName;

    public ChatClient1() throws IOException {
        selector= Selector.open();
        InetSocketAddress localhost = new InetSocketAddress(HOST, PORT);
        socketChannel= SocketChannel.open(localhost);
        socketChannel.configureBlocking(false);
        socketChannel.register(selector,SelectionKey.OP_READ);
        userName =socketChannel.getLocalAddress().toString();
    }
    //发送消息
    public void send(String msg){
        msg =userName+":"+msg;
        //发送数据
        ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
        try {
            socketChannel.write(wrap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read(){
        //发送数据
        try {
            int select = selector.select();
            if(select>0){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey next = iterator.next();
                    if(next.isReadable()){
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer allocate = ByteBuffer.allocate(1024);
                        channel.read(allocate);
                        System.out.println(new String(allocate.array()).trim());
                    }
                    iterator.remove();//删除当前的selectionkey 防止重复操作
                }
            }else {
//                System.out.println("没有可用通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        ChatClient1 chatClient1 = new ChatClient1();
        new Thread(() -> {
            while (true){
                chatClient1.read();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            chatClient1.send(s);
        }
    }
}
